var app = getApp();

var WxParse = require('../resource/wxParse/wxParse.js');

Page(Object.assign({},{
    data:{
        siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
        datalist : [],
        inited : false,
        t : 0,
        swiperIndex : 0,
        mess : '',
        pcard : '',
        paytype : 0,
        ucardtips : [],
        isshowtip : false,
        isneedback : 0,
        isauthed : false,
    },
    onShow(){
        if(this.data.isneedback == 1){
            wx.navigateBack();
        }
    },
    onLoad:function(options){
        var self = this;
        if( options.scene ){
            var list = options.scene.split('_');
            options.pid = list[0] ? list[0] : 0;
            options.zfid = list[1] ? list[1] : 0;
        }
        this.data.options = options;

        var pid = options.pid ? options.pid : ( options.scene ? options.scene : 0 );
        var zfid = options.zfid ? options.zfid : 0;

        app.com.auth(function(user){

            var postdata = {
                op:'info',
                pid:pid,
                zfid:zfid,
                pagename : 'buycard',
            }

            app.com.http('ucard','POST',postdata,0,false,function(res){
                if (res.data && !res.data.errno) {

                    if(res.data.data.params.pencardt == 2){
                        self.setData({
                            isneedback : 1,
                        })
                        wx.navigateTo({
                            url : '/zofui_sales/ucard/apply',
                        })
                        return false;
                    }else if(res.data.data.params.pencardt == 3){
                        app.com.alert('功能已关闭',function(){
                            wx.navigateBack();
                        });
                    }

                    self.setData({
                        Pagetheme : res.data.data.params.style,
                        pid : pid,
                        params : res.data.data.params,
                        cardinfo : res.data.data.cardinfo,
                        allcard : res.data.data.allcard,
                        userinfo : res.data.data.userinfo,
                        name : res.data.data.userinfo.name ? res.data.data.userinfo.name : '',
                        tel : res.data.data.userinfo.tel ? res.data.data.userinfo.tel : '',
                        sharedata : res.data.data.sharedata,
                        prizelist : res.data.data.prizelist ? res.data.data.prizelist : [],
                        ucardtips : res.data.data.ucardtips ? res.data.data.ucardtips : [],
                    },function(){
                        self.setData({
                            inited : true,
                            t : self.data.cardinfo.cardpy == 0 ? 0 : ( self.data.cardinfo.cardpm == 0 ? 1 : 2 ),
                        });
                        var index = 0;
                        
                        if( pid ){
                            for (var i = 0; i < self.data.prizelist.length; i++) {
                                if( self.data.prizelist[i].id == pid ){
                                    index = i;
                                }
                            }
                        }
                        self.setPrizeinfo(index);
                    });

                    wx.setNavigationBarTitle({
                      title:  res.data.data.cardinfo.cardname,
                    });

                    // 关闭下拉刷新
                    wx.stopPullDownRefresh();
                }
            });
        });
    },
    toggleDetail(){
        this.setData({
            showDetail : !this.data.showDetail,
        })
    },
    onPullDownRefresh: function () {
        if( this.data.isdown ) return false;
        this.data.isdown = true;
        this.onLoad( this.data.options );
        this.data.isdown = false;

        wx.stopPullDownRefresh();
    },
    onShareAppMessage : function(){
        var self = this;
        return {
            title: self.data.sharedata.title,
            path: self.data.sharedata.path,
            imageUrl : self.data.sharedata.img,
        }
    },
    confirmbuy(){
        if(this.data.buyytype == 2){
            this.confirmb(1);
        }else{
            this.buyit(1);
        }
        this.hidetip();
    },
    buyit(e){
        var self = this;
        
        if( !self.data.name ) {
            app.com.toast('请填写姓名');
            return false;
        }
        if( !app.com.verify('mobile', self.data.tel ) ) {
            app.com.toast('请填写正确的电话号码');
            return false;
        }
        if( self.data.t < 0 ) {
            app.com.toast('请选择会员卡时间');
            return false;
        }
        this.data.buyytype = 1;

        if(this.data.params.needauth == 1 && !this.data.isauthed){
            this.selectComponent('#loginauth').hideauth();
            return false;
        }

        if(self.data.params.bcdtip*1 == 1 && e != 1){
            this.hidetip();
            return false;
        }

        var postdata = {
            op:'pay',
            name:self.data.name,
            tel:self.data.tel,
            pcard : self.data.pcard,
            address : self.data.address ? self.data.address : '',
            t : self.data.t,
            street : self.data.street ? self.data.street : '',
            mess : self.data.mess ? self.data.mess : '',
            paytype : self.data.paytype ? self.data.paytype : '',
        };

        app.com.http('ucard','POST',postdata,0,true,'','',function(res){
            if (!res.data.errno) {
                if( res.data.data.payed == 1 ){
                    app.com.toast('已开通会员','success',function(){
                        var pages = getCurrentPages();
                        if( pages.length >= 2 ){
                            var prevPage = pages[pages.length - 2];
                            prevPage.setData({
                                'userinfo.level' : 1,
                                'userinfo.endtime' : postdata.t == 0 ? '一年后' : '一月后',
                            });
                        }
                        wx.navigateBack();
                    });
                }else{
                    wx.requestPayment({
						'appId' : res.data.data.appId,
                        'timeStamp': res.data.data.timeStamp,
                        'nonceStr': res.data.data.nonceStr,
                        'package': res.data.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.data.paySign,
                        'success': function (payres) {
                            if( payres.errMsg == 'requestPayment:ok' ){
                                app.com.toast('已开通会员','success',function(){

                                    var pages = getCurrentPages();
                                    if( pages.length >= 2 ){
                                        var prevPage = pages[pages.length - 2];
                                        prevPage.onPullDownRefresh();
                                    }
                                    wx.navigateBack();
                                });
                            }
                        },
                        'fail': function (payres) {
                            console.log(payres);
                        }
                    });
                }
            }else{
                app.com.alert(res.data.message);
            }
        });
    },
    confirmb(e){
        var self = this;
        
        if( !self.data.name ) {
            app.com.toast('请填写姓名');
            return false;
        }
        if( !app.com.verify('mobile', self.data.tel ) ) {
            app.com.toast('请填写正确的电话号码');
            return false;
        }
        if( self.data.params.taketype == 1 && !self.data.street ) {
            app.com.toast('请填写街道地址');
            return false;
        }
        if( self.data.params.taketype == 1 && !self.data.address ) {
            app.com.toast('请选择地区');
            return false;
        }

        this.data.buyytype = 2;
        if(this.data.params.needauth == 1 && !this.data.isauthed){
            this.selectComponent('#loginauth').hideauth();
            return false;
        }

        if(self.data.params.bcdtip*1 == 1 && e != 1){
            this.hidetip();
            return false;
        }

        var pidarr = [];
        if(this.data.actdata.getnum > 0){
            for (var i = 0; i < this.data.actdata.list.length; i++) {
                if( this.data.actdata.list[i].checked == 1 ){
                    pidarr.push(this.data.actdata.list[i].id);
                }
            }
            if(pidarr.length != this.data.actdata.getnum){
                app.com.toast('礼品需要任选'+this.data.actdata.getnum+'件');
                return false;
            }
        }

        var postdata = {
            op:'payprize',
            prizeid : self.data.actdata.id,
            name:self.data.name,
            tel:self.data.tel,
            pcard:self.data.pcard,
            address : self.data.address ? self.data.address : '',
            street : self.data.street ? self.data.street : '',
            mess : self.data.mess ? self.data.mess : '',
            paytype : self.data.paytype && self.data.actdata && self.data.actdata.isupay != 1  ? self.data.paytype : '',
            pidarr : pidarr.length > 0 ? JSON.stringify(pidarr) : '',
        };

        app.com.http('ucard','POST',postdata,0,true,'','',function(res){
            if (!res.data.errno) {

                if(res.data.data.payed == 1){
                    self.paysuc();
                    return false;
                }

                wx.requestPayment({
					'appId' : res.data.data.appId,
                    'timeStamp': res.data.data.timeStamp,
                    'nonceStr': res.data.data.nonceStr,
                    'package': res.data.data.package,
                    'signType': 'MD5',
                    'paySign': res.data.data.paySign,
                    'success': function (payres) {
                        if( payres.errMsg == 'requestPayment:ok' ){
                            self.paysuc();
                        }
                    },
                    'fail': function (payres) {
                        console.log(payres);
                    }
                });
            }else{
                app.com.alert(res.data.message);
            }
        });
    },
    paysuc(){
        app.com.toast('下单成功','success',function(){
            var pages = getCurrentPages();
            if( pages.length >= 2 ){
                var prevPage = pages[pages.length - 2];
                prevPage.onPullDownRefresh();
            }
            wx.navigateBack();
        });
    },
    bindRegionChange : function(e){
        var self = this;
        self.setData({
            address : e.detail.value[0] +','+e.detail.value[1] +','+e.detail.value[2]
        })
    },
    selectarea(){
        this.selectComponent('#ausarea').show();
    },
    authed(e){
        this.setData({
            'params.needauth' : false,
            isauthed : true,
        })
        if(this.data.buyytype == 2){
            this.confirmb();
        }else{
            this.buyit();
        }
    },
    swiperChange(e){
        this.setPrizeinfo(e.detail.current);
    },
    tabpay(e){
        this.setData({
            paytype : e.currentTarget.dataset.type
        })
    },
    shareit(){
        this.selectComponent('#poster').onClose();
    },
    bindCode(){
        this.selectComponent("#ucardcode").showfn();
    },
    codesuccess(e){
        wx.navigateBack();
    },
    setPrizeinfo(index){
        var self = this;
        self.setData({
            swiperIndex: index
        });
        var octoparse = require('../resource/wxParse/html2json2.js');
        for (var i = 0; i < self.data.prizelist.length; i++) {
            if( i == index ){
                self.setData({
                    actdata : self.data.prizelist[i],
                });
                if( self.data.prizelist[i].content ){
                    
                    var transData = octoparse.parse(self.data.prizelist[i].content);                   
                    self.setData({
                        nodes : transData,
                    })
                }else{
                    self.setData({
                        nodes : false,
                    });
                }
                return false;
            }
        }
    },
    selectprize(e){

        if(this.data.actdata.getnum > 0){
            var index = e.currentTarget.dataset.i;
            var ischecked = this.data.actdata.list[index].checked;

            if( !ischecked ){
                var acted = 0;
                for (var i = 0; i < this.data.actdata.list.length; i++) {
                    if( this.data.actdata.list[i].checked == 1 ){
                        acted ++;
                    }
                }
                if(acted >= this.data.actdata.getnum){
                    app.com.toast('最多选择'+this.data.actdata.getnum+'件');
                    return false;
                }
            }
            this.setData({
                ['actdata.list['+index+'].checked'] : ischecked == 1 ? 0 : 1,
            });
        }

    },
    hidetip(){
        this.setData({
            isshowtip : !this.data.isshowtip
        })
    },
    chooseCard(e){
        this.setData({
            t : e.detail.value
        })
    },
    changeinput(e){
        var key = e.currentTarget.dataset.name;
        this.setData({
            [key] : e.detail.value
        })
    },
    buyprize(e){

        var pidarr = [];
        if(this.data.actdata.getnum > 0){
            for (var i = 0; i < this.data.actdata.list.length; i++) {
                if( this.data.actdata.list[i].checked == 1 ){
                    pidarr.push(this.data.actdata.list[i].id);
                }
            }
            if(pidarr.length != this.data.actdata.getnum){
                app.com.toast('礼品需要任选'+this.data.actdata.getnum+'件');
                return false;
            }
        }
        
        this.setData({
            showconfirm : true
        })
    },
    togglece(e){
        this.setData({
            showconfirm : false
        })
    },
    location : function( e ){
        app.com.location( e );
    },
    otherapp : function( e ){
        app.com.otherapp( e );
    },
    navigateto : function( e ){
        app.com.navigateto( e,this.data.tid );
    },
    redirectto : function( e ){
        app.com.redirectto( e,this.data.tid );
    },    
    callphone : function(e){
        app.com.callphone( e );
    },
    showimages : function( e ){
        app.com.showimages( e );
    },
    FormIdsubmit : function(e){
        if( app.globalData.formarr.length <= 20 ) app.globalData.formarr.push(e.detail.formId);
    },
    
}))